package com.spring.controller;

import com.spring.Aspect.HelloWorld;
import com.spring.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.ServletContextAware;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.support.RequestContextUtils;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
public class MyIndex implements ServletContextAware{

    /** 实现 ServletContextAware 接口的类，实现 setServletContext 方法，都可以取得ServletContext */
    private ServletContext servletContext;

    @Autowired
    private HelloWorld helloWorld;

    @Autowired
    private LoginService loginService;

    @RequestMapping({ "/index.do" })
    public ModelAndView admin_list(String name, HttpServletRequest request, HttpServletResponse response) {

        ModelAndView mv = new ModelAndView("index" );
        mv.addObject("userRole", "ADMIN");
        helloWorld.doPrint();

        //loginService.register("lksdfsd","上45345");

        //spring上下文
        WebApplicationContext ac1 = WebApplicationContextUtils.
                getWebApplicationContext(request.getSession().getServletContext());
        //spingmvc的上下文
        WebApplicationContext ac2= RequestContextUtils.
                getWebApplicationContext(request);

        UserDetails userDetails = (UserDetails) SecurityContextHolder.
                getContext().getAuthentication() .getPrincipal();
        System.out.println(userDetails.getUsername());
        return mv;
    }





    @Override
    public void setServletContext(ServletContext servletContext) {
        this.servletContext = servletContext;
    }
}
